package com.mc.read.pcApi.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.mc.read.common.constant.Constants;
import com.mc.read.common.emun.ServiceCodeEnum;
import com.mc.read.common.exception.ServiceException;
import com.mc.read.dao.mapper.*;
import com.mc.read.dao.models.*;
import com.mc.read.dao.vo.LabelVo;
import com.mc.read.dao.vo.PageVo;
import com.mc.read.vo.request.BaseRequest;
import com.mc.read.vo.respose.BaseRespose;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
 * @author liuhao
 * @date 2019/6/5 15:16
 */
@Service
@Slf4j
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
public class MainService {
    @Autowired
    UserinformationMapper userinformationMapper;
    @Autowired
    BookinformationMapper bookinformationMapper;
    @Autowired
    BooklabelMapper booklabelMapper;
    @Autowired
    UserbooklabelMapper userbooklabelMapper;
    @Autowired
    UserinformationdetMapper userinformationdetMapper;
    @Autowired
    LabelauditMapper labelauditMapper;
    @Autowired
    SecondleveltypeforuserMapper secondleveltypeforuserMapper;
    @Autowired
    SecondleveltypestaMapper secondleveltypestaMapper;
    @Autowired
    FunctionService functionService;

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 查询该书籍所有标签列表 selectBookLabelList
     **/
    public BaseRespose selectBookLabelList(BaseRequest baseRequest) {
        log.info("查询该书籍所有标签列表,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Bookinformation bookinformation = null;
        try {
            bookinformation = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Bookinformation.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        BooklabelCustom booklabelCustom = new BooklabelCustom();
        booklabelCustom.setBookid(bookinformation.getBookinformationid());
        booklabelCustom.setUserid(baseRequest.getUserId());
        //查询标签详情
        List<BooklabelCustom> booklabelCustomList = booklabelMapper.selectLabelAllList(booklabelCustom);
        baseRespose.setReturnString(booklabelCustomList);
        return baseRespose;
    }


    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 用户给书籍标签点赞 userGiveLike
     **/
    public BaseRespose userGiveLike(BaseRequest baseRequest) {
        log.info("用户给书籍标签点赞,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Userbooklabel userbooklabel = null;
        try {
            userbooklabel = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Userbooklabel.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(userbooklabel.getBooklabelid())) {
            throw new ServiceException(203020, "书籍标签不能为空", JSON.toJSONString(baseRequest));
        }


        UserbooklabelExample example = new UserbooklabelExample();
        example.createCriteria().andUseridEqualTo(baseRequest.getUserId()).andBooklabelidEqualTo(userbooklabel.getBooklabelid()).andTypeEqualTo(1);
        List<Userbooklabel> userbooklabelList = userbooklabelMapper.selectByExample(example);
        if (userbooklabelList.size() > 0) {
            throw new ServiceException(203020, "已点过赞了", JSON.toJSONString(baseRequest));
        }
        Booklabel booklabel = booklabelMapper.selectByPrimaryKey(userbooklabel.getBooklabelid());
        if (ObjectUtils.isEmpty(booklabel)) {
            throw new ServiceException(203020, "未找到该标签", JSON.toJSONString(baseRequest));
        }
        //查询这本书 点过几次赞
        LabelVo labelVo = new LabelVo();
        labelVo.setType(1);
        labelVo.setBookid(booklabel.getBookid());
        labelVo.setUserid(baseRequest.getUserId());
        Long count = userbooklabelMapper.selectCount(labelVo);
        if (count >= 5) {
            throw new ServiceException(203020, "对同一本书 只能点赞5次", JSON.toJSONString(baseRequest));
        }
        booklabelMapper.updateLikeSum(userbooklabel.getBooklabelid());
        userbooklabel.setType(1);
        userbooklabel.setUserid(baseRequest.getUserId());
        userbooklabelMapper.insertSelective(userbooklabel);
        baseRespose.setReturnString(" ");
        Userinformationdet userinformationdet = new Userinformationdet();
        userinformationdet.setUserid(baseRequest.getUserId());
        userinformationdet.setExperience(Constants.LIKE_EXP);
        userinformationdetMapper.updateExperience(userinformationdet);
        functionService.updateFunctionClick("标签点赞");

        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 用户给书籍标签狂踩 userGivehate
     **/
    public BaseRespose userGivehate(BaseRequest baseRequest) {
        log.info("用户给书籍标签狂踩,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Userbooklabel userbooklabel = null;
        try {
            userbooklabel = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Userbooklabel.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(userbooklabel.getBooklabelid())) {
            throw new ServiceException(203020, "书籍标签不能为空", JSON.toJSONString(baseRequest));
        }
        UserbooklabelExample example = new UserbooklabelExample();
        example.createCriteria().andUseridEqualTo(baseRequest.getUserId()).andBooklabelidEqualTo(userbooklabel.getBooklabelid()).andTypeEqualTo(2);
        List<Userbooklabel> userbooklabelList = userbooklabelMapper.selectByExample(example);
        if (userbooklabelList.size() > 0) {
            throw new ServiceException(203020, "已踩过了", JSON.toJSONString(baseRequest));
        }
        Booklabel booklabel = booklabelMapper.selectByPrimaryKey(userbooklabel.getBooklabelid());
        if (ObjectUtils.isEmpty(booklabel)) {
            throw new ServiceException(203020, "未找到该标签", JSON.toJSONString(baseRequest));
        }
        //查询这本书 点过几次赞
        LabelVo labelVo = new LabelVo();
        labelVo.setType(2);
        labelVo.setBookid(booklabel.getBookid());
        labelVo.setUserid(baseRequest.getUserId());
        Long count = userbooklabelMapper.selectCount(labelVo);
        if (count >= 5) {
            throw new ServiceException(203020, "对同一本书 只能狂踩5次", JSON.toJSONString(baseRequest));
        }
        booklabelMapper.updateHateSum(userbooklabel.getBooklabelid());
        userbooklabel.setType(2);
        userbooklabel.setUserid(baseRequest.getUserId());
        userbooklabelMapper.insertSelective(userbooklabel);
        Userinformationdet userinformationdet = new Userinformationdet();
        userinformationdet.setUserid(baseRequest.getUserId());
        userinformationdet.setExperience(Constants.HATE_EXP);
        userinformationdetMapper.updateExperience(userinformationdet);
        functionService.updateFunctionClick("标签狂踩");

        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 用户给该书籍添加标签 userAddLabel
     **/
    public BaseRespose userAddLabel(BaseRequest baseRequest) {
        log.info("用户给该书籍添加标签,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Labelaudit labelaudit = null;
        try {
            labelaudit = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Labelaudit.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(labelaudit.getBookid())) {
            throw new ServiceException(203020, "请选择书籍", JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(labelaudit.getLabelname())) {
            throw new ServiceException(203020, "请输入标签名称", JSON.toJSONString(baseRequest));
        }
        List<Booklabel> booklabelList = booklabelMapper.selectByLabelName(labelaudit);
        if (booklabelList.size() > 0) {
            throw new ServiceException(203020, "该书籍已存在该标签", JSON.toJSONString(baseRequest));
        }
        BooklabelExample booklabelExample=new BooklabelExample();
        booklabelExample.createCriteria().andBookidEqualTo(labelaudit.getBookid());
        int count=booklabelMapper.countByExample(booklabelExample);
        if(count>=Constants.BOOK_SUM_LABEL){
            throw new ServiceException(203020, "该书籍的标签已满", JSON.toJSONString(baseRequest));
        }
        LabelauditExample example = new LabelauditExample();
        example.createCriteria().andBookidEqualTo(labelaudit.getBookid()).andLabelnameEqualTo(labelaudit.getLabelname());
        List<Labelaudit> labelauditList = labelauditMapper.selectByExample(example);
        if (labelauditList.size() == 0) {
            labelaudit.setUserid(baseRequest.getUserId());
            labelaudit.setCreatedate(new Date());
            labelauditMapper.insertSelective(labelaudit);
        } else {
            labelaudit = labelauditList.get(0);
            if (labelaudit.getStatus() == 0) {
                throw new ServiceException(203020, "该标签正在审核中，请耐心等待管理人员审核", JSON.toJSONString(baseRequest));
            } else if (labelaudit.getStatus() == 2) {
                throw new ServiceException(203020, "无法添加该标签，理由为：" + labelaudit.getNopasstxt(), JSON.toJSONString(baseRequest));
            }
        }
        baseRespose.setReturnString(" ");
        functionService.updateFunctionClick("添加标签");

        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 小说书籍查询 selectBookList
     **/
    public BaseRespose selectBookList(BaseRequest baseRequest) {
        log.info("小说书籍查询,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        PageVo pageVo = null;
        try {
            pageVo = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), PageVo.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(pageVo.getSelectinfo())) {
            throw new ServiceException(203020, "查询内容不能为空", JSON.toJSONString(baseRequest));
        }
        PageHelper.startPage(pageVo.getPagenum(), pageVo.getPagesize());
        PageHelper.orderBy("readnum desc");
        BookinformationExample example = new BookinformationExample();
        example.createCriteria().andBooknameLike(pageVo.getSelectinfo());
        example.or().andAuthorLike(pageVo.getSelectinfo());
        baseRespose.setReturnString(bookinformationMapper.selectByExample(example));
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 用户对书籍二级菜单选举 addSecondLevel
     **/
    public BaseRespose addSecondLevel(BaseRequest baseRequest) {
        log.info("用户对书籍二级菜单选举,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Secondleveltypeforuser secondleveltypeforuser = null;
        try {
            secondleveltypeforuser = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Secondleveltypeforuser.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(secondleveltypeforuser.getBookid()) || ObjectUtils.isEmpty(secondleveltypeforuser.getSecondlevelid()) || ObjectUtils.isEmpty(secondleveltypeforuser.getSecondlevelname())) {
            throw new ServiceException(203020, "请求参数不足", JSON.toJSONString(baseRequest));
        }
        SecondleveltypeforuserExample userExample = new SecondleveltypeforuserExample();
        userExample.createCriteria().andBookidEqualTo(secondleveltypeforuser.getBookid()).andUseridEqualTo(baseRequest.getUserId());
        List<Secondleveltypeforuser> secondleveltypeforuserList = secondleveltypeforuserMapper.selectByExample(userExample);
        if(secondleveltypeforuserList.size()>0){
            throw new ServiceException(203020, "您已经选择过了，请勿重复选择",JSON.toJSONString(baseRequest));
        }

        int i = secondleveltypestaMapper.updateSum(secondleveltypeforuser);
        if (i == 0) {
            Secondleveltypesta secondleveltypesta = new Secondleveltypesta();
            secondleveltypesta.setBookid(secondleveltypeforuser.getBookid());
            secondleveltypesta.setSecondlevelid(secondleveltypeforuser.getSecondlevelid());
            secondleveltypesta.setSecondlevelname(secondleveltypeforuser.getSecondlevelname());
            secondleveltypesta.setSum(1);
            secondleveltypestaMapper.insertSelective(secondleveltypesta);
        }
        secondleveltypeforuser.setUserid(baseRequest.getUserId());
        secondleveltypeforuserMapper.insertSelective(secondleveltypeforuser);
        SecondleveltypestaExample example = new SecondleveltypestaExample();
        example.createCriteria().andBookidEqualTo(secondleveltypeforuser.getBookid()).andSecondlevelidEqualTo(secondleveltypeforuser.getSecondlevelid());
        List<Secondleveltypesta> secondleveltypestaList = secondleveltypestaMapper.selectByExample(example);
        if (secondleveltypestaList.get(0).getSum() >= Constants.SEC_SUM) {
            Bookinformation bookinformation = new Bookinformation();
            bookinformation.setBookinformationid(secondleveltypeforuser.getBookid());
            bookinformation.setSecondlevelid(secondleveltypeforuser.getSecondlevelid());
            bookinformation.setSecondlevelname(secondleveltypeforuser.getSecondlevelname());
            bookinformationMapper.updateByPrimaryKeySelective(bookinformation);
            //删除选举和用户的中间表信息
            SecondleveltypeforuserExample secondleveltypeforuserExample = new SecondleveltypeforuserExample();
            secondleveltypeforuserExample.createCriteria().andBookidEqualTo(secondleveltypeforuser.getBookid());
            secondleveltypeforuserMapper.deleteByExample(secondleveltypeforuserExample);
        }
        functionService.updateFunctionClick("二级菜单选举");

        baseRespose.setReturnString(" ");
        return baseRespose;
    }
}
